package com.ruoyi.compensationManagement.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.compensationManagement.domain.CompensationRetireeSubsidyProject;
import com.ruoyi.compensationManagement.domain.CompensationRetirespayrollLog;
import com.ruoyi.compensationManagement.domain.vo.RetiresPayrollImportVo;
import com.ruoyi.compensationManagement.mapper.CompensationRetirespayrollLogMapper;
import com.ruoyi.compensationManagement.service.ICompensationRetirespayrollLogService;
import org.apache.poi.hpsf.Decimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.compensationManagement.mapper.CompensationRetirespayrollMapper;
import com.ruoyi.compensationManagement.domain.CompensationRetirespayroll;
import com.ruoyi.compensationManagement.service.ICompensationRetirespayrollService;

/**
 * 退休人员补贴工资Service业务层处理
 *
 * @author zy
 * @date 2022-10-07
 */
@Service
public class CompensationRetirespayrollServiceImpl implements ICompensationRetirespayrollService {
    @Autowired
    private CompensationRetirespayrollMapper compensationRetirespayrollMapper;

    @Autowired
    private ICompensationRetirespayrollLogService compensationRetirespayrollLogService;

    private static final Logger log = LoggerFactory.getLogger(CompensationRetirespayrollServiceImpl.class);

    /**
     * 查询退休人员补贴工资
     *
     * @param retireespayrollId 退休人员补贴工资主键
     * @return 退休人员补贴工资
     */
    @Override
    public CompensationRetirespayroll selectCompensationRetirespayrollByRetireespayrollId(Long retireespayrollId) {
        return compensationRetirespayrollMapper.selectCompensationRetirespayrollByRetireespayrollId(retireespayrollId);
    }

    /**
     * 查询退休人员补贴工资（浮动项目）
     *
     * @param retireespayrollId 退休人员补贴工资主键
     * @return 退休人员补贴工资
     */
    @Override
    public List<CompensationRetireeSubsidyProject> selectfFoatingItemsByRetireespayrollId(Long retireespayrollId) {
        String json = compensationRetirespayrollMapper.selectFloatingItemsJson(retireespayrollId);
        return JSON.parseArray(json, CompensationRetireeSubsidyProject.class);
    }


    /**
     * 查询退休人员补贴工资列表
     *
     * @param compensationRetirespayroll 退休人员补贴工资
     * @return 退休人员补贴工资
     */
    @Override
    public List<CompensationRetirespayroll> selectCompensationRetirespayrollList(CompensationRetirespayroll compensationRetirespayroll) {
        List<CompensationRetirespayroll> compensationRetirespayrolls = compensationRetirespayrollMapper.selectCompensationRetirespayrollList(compensationRetirespayroll);
        for (CompensationRetirespayroll item : compensationRetirespayrolls) {
            BigDecimal floatTotal = new BigDecimal("0");
            item.setFloatingItems(JSON.parseArray(item.getFloatingItemsSql(), CompensationRetireeSubsidyProject.class));
            if (item.getFloatingItems() != null) {
                for (CompensationRetireeSubsidyProject floatingItem : item.getFloatingItems()) {
                    floatTotal = floatTotal.add(floatingItem.getSubsidyprojectMoney());
                }
            }
            item.setFloatTotal(floatTotal);
        }
        return compensationRetirespayrolls;
    }

    /**
     * 新增退休人员补贴工资
     *
     * @param compensationRetirespayroll 退休人员补贴工资
     * @return 结果
     */
    @Override
    public int insertCompensationRetirespayroll(CompensationRetirespayroll compensationRetirespayroll) {
        //将浮动项目数组对象转换为字符串存储数据库
        compensationRetirespayroll.setFloatingItemsSql(JSON.toJSONString(compensationRetirespayroll.getFloatingItems()));
        return compensationRetirespayrollMapper.insertCompensationRetirespayroll(compensationRetirespayroll);
    }

    /**
     * 修改退休人员补贴工资
     *
     * @param compensationRetirespayroll 退休人员补贴工资
     * @return 结果
     */
    @Override
    public int updateCompensationRetirespayroll(CompensationRetirespayroll compensationRetirespayroll) {

        //将浮动项目数组对象转换为字符串存储数据库
        compensationRetirespayroll.setFloatingItemsSql(JSON.toJSONString(compensationRetirespayroll.getFloatingItems()));

        //从数据库拿旧记录
        CompensationRetirespayroll old = selectCompensationRetirespayrollByRetireespayrollId(compensationRetirespayroll.getRetireespayrollId());

        //利用StringBuilder收集数据
        StringBuilder builder = new StringBuilder();

        if (old.getLivingallowance().compareTo(compensationRetirespayroll.getLivingallowance()) != 0) {
            builder.append("【生活补贴】:由" + old.getLivingallowance() + "改动为==>" + compensationRetirespayroll.getLivingallowance());
            builder.append("\n");
        }
        if (old.getHousingreformsubsidies().compareTo(compensationRetirespayroll.getHousingreformsubsidies()) != 0) {
            builder.append("【住房改革补贴】:由" + old.getHousingreformsubsidies() + "改动为==>" + compensationRetirespayroll.getHousingreformsubsidies());
            builder.append("\n");
        }
        if (old.getSolatiumforretirees().compareTo(compensationRetirespayroll.getSolatiumforretirees()) != 0) {
            builder.append("【退休人员慰问金】:由" + old.getSolatiumforretirees() + "改动为==>" + compensationRetirespayroll.getSolatiumforretirees());
            builder.append("\n");
        }

        //循环后端从数据库查到的浮动项与前端传进来的浮动项比较值是否相等
        for (CompensationRetireeSubsidyProject oldFloat : JSON.parseArray(old.getFloatingItemsSql(), CompensationRetireeSubsidyProject.class)) {
            for (CompensationRetireeSubsidyProject newFloat : compensationRetirespayroll.getFloatingItems()) {
                if (newFloat.getSubsidyprojectId().longValue() == oldFloat.getSubsidyprojectId().longValue()) {
                    //浮动项新旧值不相等
                    if (newFloat.getSubsidyprojectMoney().compareTo(oldFloat.getSubsidyprojectMoney()) != 0) {
                        builder.append("【" + newFloat.getSubsidyprojectName() + "】" + "：由" + oldFloat.getSubsidyprojectMoney() + "改动为==>" + newFloat.getSubsidyprojectMoney());
                        builder.append("\n");
                    }
                }
            }
        }
        if (old.getRetireesPayrollTotal().compareTo(compensationRetirespayroll.getRetireesPayrollTotal()) != 0) {
            builder.append("【金额合计】:由" + old.getRetireesPayrollTotal() + "改动为==>" + compensationRetirespayroll.getRetireesPayrollTotal());
            builder.append("\n");
        }

        CompensationRetirespayrollLog compensationRetirespayrollLog = new CompensationRetirespayrollLog();
        compensationRetirespayrollLog.setRetireesPayrollId(compensationRetirespayroll.getRetireespayrollId());
        compensationRetirespayrollLog.setLogInfo(builder.toString());
        compensationRetirespayrollLog.setLogDate(new Date());
        compensationRetirespayrollLogService.insertCompensationRetirespayrollLog(compensationRetirespayrollLog);
        return compensationRetirespayrollMapper.updateCompensationRetirespayroll(compensationRetirespayroll);
    }

    /**
     * 批量删除退休人员补贴工资
     *
     * @param retireespayrollIds 需要删除的退休人员补贴工资主键
     * @return 结果
     */
    @Override
    public int deleteCompensationRetirespayrollByRetireespayrollIds(Long[] retireespayrollIds) {
        return compensationRetirespayrollMapper.deleteCompensationRetirespayrollByRetireespayrollIds(retireespayrollIds);
    }

    /**
     * 删除退休人员补贴工资信息
     *
     * @param retireespayrollId 退休人员补贴工资主键
     * @return 结果
     */
    @Override
    public int deleteCompensationRetirespayrollByRetireespayrollId(Long retireespayrollId) {
        return compensationRetirespayrollMapper.deleteCompensationRetirespayrollByRetireespayrollId(retireespayrollId);
    }

    /**
     * 确定退休人员补贴工资表
     */
    @Override
    public int determiningPayrollRetirees(CompensationRetirespayroll compensationRetirespayroll) {
        return compensationRetirespayrollMapper.determiningPayrollRetirees(compensationRetirespayroll);
    }


    /**
     * 计算工资
     */
    @Override
    public BigDecimal calculateRetirementWages(CompensationRetirespayroll compensationRetirespayroll) {
        //计算固定项目金额合计
        BigDecimal fixedItems = new BigDecimal("0");
        fixedItems = fixedItems.add(compensationRetirespayroll.getLivingallowance());
        fixedItems = fixedItems.add(compensationRetirespayroll.getHousingreformsubsidies());
        fixedItems = fixedItems.add(compensationRetirespayroll.getSolatiumforretirees());

        //计算浮动项目金额合计
        BigDecimal floatingItems = new BigDecimal("0");
        if (!StringUtils.isEmpty(compensationRetirespayroll.getFloatingItems())) {
            for (CompensationRetireeSubsidyProject floatingItem : compensationRetirespayroll.getFloatingItems()) {
                if (StringUtils.isNotNull(floatingItem.getSubsidyprojectId()) && StringUtils.isNotNull(floatingItem.getSubsidyprojectName()) && StringUtils.isNotNull(floatingItem.getSubsidyprojectMoney())) {
                    floatingItems = floatingItems.add(floatingItem.getSubsidyprojectMoney());
                }
            }
        }
        //计算总金额合计
        BigDecimal payrollTotal = new BigDecimal("0");
        payrollTotal = payrollTotal.add(fixedItems);
        payrollTotal = payrollTotal.add(floatingItems);
        return payrollTotal;
    }

    /**
     * 是否查询自身补贴工资
     */
    @Override
    public int isItSelfRetireesPayroll(CompensationRetirespayroll compensationRetirespayroll) {
        return compensationRetirespayrollMapper.isItSelfRetireesPayroll(compensationRetirespayroll);
    }

    @Override
    public String importRetireesPayroll(List<RetiresPayrollImportVo> RetireesPayrollList) {
        if (StringUtils.isNull(RetireesPayrollList) || RetireesPayrollList.size() == 0) {
            throw new ServiceException("导入工资数据不能为空！");
        }
        int totalNum = RetireesPayrollList.size();
        int Num = 2;
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RetiresPayrollImportVo retiresPayrollImportVo : RetireesPayrollList) {
            try {
                if (retiresPayrollImportVo.getJobNumber() == null || retiresPayrollImportVo.getJobNumber().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,工号未填");
                    Num++;
                    continue;
                }
                if (retiresPayrollImportVo.getNickName() == null || retiresPayrollImportVo.getNickName().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,姓名未填");
                    Num++;
                    continue;
                }
                if (retiresPayrollImportVo.getRetireespayrollDate() == null || retiresPayrollImportVo.getRetireespayrollDate().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,工资年月未填");
                    Num++;
                    continue;
                }

                //执行导入
                compensationRetirespayrollMapper.importData(retiresPayrollImportVo);

                successNum++;
                Num++;
                successMsg.append("<br/>" + "数据：" + successNum + "、姓名:" + retiresPayrollImportVo.getNickName() + "，退休人员补贴工资导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + "第" + Num + "行,导入失败。请检查是否准确填写";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，部分导入失败！本次导入Excel数据共" + totalNum + "条，其中成功导入" + successNum + "条" + ",共 " + failureNum + " 条数据格式不正确导入失败（请另外下载新模板将失败数据重新导入），错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！本次导入Excel数据共" + totalNum + "条，" + "其中，共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
